package com.zhiyun.hxzy.service;

import com.zhiyun.hxzy.dao.ProgrammerDao;
import com.zhiyun.hxzy.domain.Programmer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Service
@Transactional
public class ProgrammerService {
    @Autowired
    private ProgrammerDao programmerDao;

    public void addProgrammer(Programmer programmer) {
        programmerDao.save(programmer);
    }

    public void updateStatus(Long[] ids, Integer status) {
        for (Long idss : ids) {
            Programmer programmer = programmerDao.getOne(idss);
            programmer.setStatus(status);
            programmerDao.save(programmer);
        }
    }



    public Page<Programmer> findAll(int pageNum, int pageSize) {
        if (pageNum < 0) {
            pageNum = 0;
        }
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        Page<Programmer> all = programmerDao.findAll(pageable);
        return all;
    }

    public Programmer findByIdProgrammer(Long id) {
        return programmerDao.getOne(id);
    }

    public void updateProgrammer(Programmer programmer) {
        programmerDao.save(programmer);
    }

    public void del(Long id) {
        programmerDao.delete(programmerDao.getOne(id));
    }

    public List<Programmer> findAllActiveProgrammer() {
        Specification<Programmer> specification = new Specification<Programmer>() {
            @Override
            public Predicate toPredicate(Root<Programmer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.like(root.get("status").as(String.class), "1");
                return predicate;
            }
        };
        return programmerDao.findAll(specification);
    }
}
